import http from './http';
import MD5 from 'crypto-js/md5';
import { message } from '@/utils/message';
import { useUserStore } from '@/stores/user';
import { showLoading,hideLoading } from '@/utils/loading';

function generateKGSignature(params:any){
  const arr=[]
  for(let k in params){
    arr.push(`${k}=${params[k]}`);
  }
  arr.sort();
  arr.unshift('NVPh5oo715z5DIWAeQlhMDsWXXQV4hwt');
  arr.push('NVPh5oo715z5DIWAeQlhMDsWXXQV4hwt');
  return MD5(arr.join('')).toString();
}
function handleJsonpCallback(text='',func='callback'){
  const reg=new RegExp(`^${func}\\((.*)\\)`,'ms');
  const t=text.match(reg)?.[1];
  if(!t) return {};
  return JSON.parse(t);
}

export function getLoginQrCode(){
  const query:any={
    appid:'1014',clientver:'8031',clienttime:`${Date.now()}`,
    mid:KgUser.getKgMid(),uuid:KgUser.getKgMid(),
    dfid:KgUser.getDfid(),
    type:'1',plat:'4',srcappid:'2919',
    qrcode_txt:'https://h5.kugou.com/apps/loginQRCode/html/index.html?appid=1014&'
  }
  query.signature=generateKGSignature(query);
  showLoading();
  return http.get('https://login-user.kugou.com/v2/qrcode',{
    query
  }).then((res:any) =>{
    if(res.status==1){
      return Promise.resolve(res.data);
    }else{
      message('error',res.data);
      return Promise.reject(res);
    }
  }).finally(() =>{
    hideLoading();
  })
}

export function checkQrCode(qrcode:string){
  if(!qrcode) return Promise.reject('参数错误');
  const query:any={
    appid:'1014',clientver:'8031',clienttime:`${Date.now()}`,
    mid:KgUser.getKgMid(),uuid:KgUser.getKgMid(),
    dfid:KgUser.getDfid(),
    plat:'4',srcappid:'2919',
    qrcode
  }
  query.signature=generateKGSignature(query);
  return http.get('https://login-user.kugou.com/v2/get_userinfo_qrcode',{
    query
  }).then((res:any) =>{
    if(res.status==1){
      return Promise.resolve(res.data);
    }else{
      return Promise.reject(res);
    }
  })
}

export function loginByToken(){
  const userStore=useUserStore();
  const t=Date.now(),token=userStore.token;
  const query:any={
    appid:'1014',clientver:'1000',clienttime:`${t}`,
    //mid:'bd53fffdc6f17b70050aebf276ca990d',uuid:'bd53fffdc6f17b70050aebf276ca990d',
    mid:KgUser.getKgMid(),uuid:KgUser.getKgMid(),
    dfid:KgUser.getDfid(),
    dev:'web',userid:`${userStore.user.id}`,
    clienttime_ms:`${t}000`,
    plat:'4',srcappid:'2919'
  }
  const e=AES.encrypt(JSON.stringify({
    token
  }))
  query.params=e.encryptedStr;
  query.pk=RSA.encrypt(JSON.stringify({
    clienttime_ms: `${t}000`,
    key: e.key
  }))
  //query.pk='4024f64af8a6d752ede0acb090e150a9c8db11f75bdb310441f2aa2da3476f24a4b7fc671a72841b1e214dd27626e5264d53ea5bad02aba72f07f87e80169ab18c54c36999a6d995765c299f007dc7895ec4d91226c837cd1af9340c30414020c30256183581b213369a5db71660ce0c48d47864c9edcd3ef1933f1c41d37a0b'
  //query.params='39b813a64dd886291bd0ee9c220b26a188d15286726e07bad9d5ce697d93e25883c23491fe7d2ef3b0bb6dc48c54751c1a88fb4fd7dfde15d94d438e08b05ee4c6489d9d893e4b001903fa7e9c437d6b'
  query.signature=generateKGSignature(query);
  return http.get('https://loginservice.kugou.com/v1/login_by_token_get',{
    query
  }).then((res:any) =>{
    if(res.status==1){
      return Promise.resolve(res.data);
    }else{
      return Promise.reject(res);
    }
  })
}

export function searchSong(keyword='',page='1',pagesize='30'){
  const userStore=useUserStore();
  const query:any={
    callback:'callback',
    appid:'1014',clientver:'1000',clienttime:`${Date.now()}`,
    mid:KgUser.getKgMid(),uuid:KgUser.getKgMid(),
    dfid:KgUser.getDfid(),
    plat:'4',srcappid:'2919',bitrate:'0',inputtype:'0',
    platform:'WebFilter',iscorrection:'1',isfuzzy:'0',
    privilege_filter:'0',filter:'10',
    keyword,page,pagesize,
    token:userStore.token,userid:`${userStore.user.id}`
  }
  query.signature=generateKGSignature(query);
  showLoading();
  return http.get('https://complexsearch.kugou.com/v2/search/song',{
    responseType:2,
    query
  }).then((res:any) =>{
    const _res=handleJsonpCallback(res);
    if(_res.status==1){
      return Promise.resolve(_res.data);
    }else{
      message('error',_res.error_msg);
      return Promise.reject(_res);
    }
  }).finally(() =>{
    hideLoading();
  })
}

export function getSongInfo(id='0'){
  const query:any={
    callback:'callback',r:'play/getdata',_: `${Date.now()}`,
    appid:'1014',mid:KgUser.getKgMid(),
    dfid:KgUser.getDfid(),platid:'4',
    encode_album_audio_id:id
  }
  return http.get('https://wwwapi.kugou.com/yy/index.php',{
    responseType:2,
    query
  }).then((res:any) =>{
    const _res=handleJsonpCallback(res);
    if(_res.status==1){
      return Promise.resolve(_res.data);
    }else{
      message('error',_res.error_code);
      return Promise.reject(_res);
    }
  })
}

export function getAudioBuffer(url:string='',buffer:SourceBuffer){
  return http.get(url,{
    responseType:3
  }).then((res:any) =>{
    buffer.appendBuffer(new Uint8Array(res).buffer);
  })
}